#!/usr/bin/python

import sys, subprocess, re, os.path, os, time
import ctags
from ctags import CTags, TagEntry

zenity = ['/usr/bin/zenity', '--list', '--width=600', '--height=300',
    '--title="tags"', '--column="tags"', '--hide-header',
    '--text="Select a window"']
tag = ""
filepath = ""

def get_gvim_winname(filepath):
    wmctrl = subprocess.Popen(["wmctrl", "-l"], stdout=subprocess.PIPE)
    grep = subprocess.Popen(["grep", "GVIM"], stdin=wmctrl.stdout, stdout=subprocess.PIPE)
    wmctrl.stdout.close()
    gvimprocs = grep.stdout.readlines()
    grep.stdout.close()

    for gvimproc in gvimprocs:
        filename = gvimproc.split()[3]
        winname = gvimproc.split()[-1]
        path = re.sub(".+\((.+)\).+", "\g<1>", gvimproc).rstrip()
        if path:
            fullpath = re.sub("~", os.getenv("HOME"), os.path.join(path, filename))

            ## Now that we cleaned everthing up, we can compare
            if filepath == fullpath:
                return winname
    return None

tagname = sys.argv[1]
# Check if projectdir environment variable exists.
if os.environ.has_key('projectdir'):
    cd = os.environ['projectdir']
    tagsfilename = os.path.join(cd, 'tags')
else:
    cd = os.getcwd()
    while not os.path.exists(os.path.join(cd, 'tags')) and cd != '/':
        cd = os.path.split(cd)[0]
    tagsfilename = os.path.join(cd, 'tags')
if os.path.exists(tagsfilename):
    tagfile = CTags(tagsfilename)
    entry = TagEntry()
    if tagfile.find(entry, tagname, ctags.TAG_FULLMATCH | ctags.TAG_OBSERVECASE):
        tag = "%s %s" % (os.path.join(cd, entry['file']), entry['pattern'].strip('/'))
        status = tagfile.findNext(entry)
        if status:
            # There's more than one file that has the tag. Display
            # a list so the user can choose
            tags = [tag, "%s %s" % (os.path.join(cd, entry['file']), entry['pattern'].strip('/'))]
            while tagfile.findNext(entry):
                tags.append("%s %s" % (os.path.join(cd, entry['file']), entry['pattern'].strip('/')))
            z = subprocess.Popen(zenity, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
            stdoutdata, stderrdata = z.communicate('\n'.join(tags))
            if stdoutdata:
                filepath = stdoutdata.split()[0]
        else:
            filepath = tag.split()[0]
    else: filepath = None

if not filepath: winname = None
else: winname = get_gvim_winname(filepath)
if winname:
    if tag:
        cmd = ["/usr/bin/gvim", "--servername", winname, "--remote-send", ":tag %s<CR>" % tagname]
        subprocess.call(cmd)
    cmd = ["wmctrl", "-a", winname]
    subprocess.call(cmd)
else:
    cmd = ["/usr/bin/gvim",]
    cmd.append(filepath)
    subprocess.call(cmd)
    while not winname:
        winname = get_gvim_winname(filepath)
        time.sleep(0.01)
    cmd = ["/usr/bin/gvim", "--servername", winname, "--remote-send", ":tag %s<CR>" % tagname]
    subprocess.call(cmd)

